<?php
namespace app\massage\controller;
use app\ApiRest;

use app\massage\model\BalanceWater;
use app\massage\model\Coach;

use app\massage\model\Config;
use app\massage\model\Goods;

use app\massage\model\Order;
use app\massage\model\Police;
use app\massage\model\RefundOrder;
use app\massage\model\RefundOrderGoods;
use app\massage\model\User;
use app\massage\model\Wallet;
use longbingcore\wxcore\WxSetting;
use think\App;
use think\facade\Db;
use think\Request;


class IndexCoach extends ApiRest
{

    protected $model;

    protected $cap_info;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Coach();

        $this->order_model = new Order();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','in',[2,3]];

        $this->cap_info = $this->model->dataInfo($cap_dis);

        if(empty($this->cap_info)){

            $this->errorMsg('你还不是技师');
        }

    }

    /**
     * @author chenniang
     * @DataTime: 2021-07-08 11:39
     * @功能说明:技师首页
     */
    public function coachIndex(){

        $data = $this->cap_info;

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 09:59
     * @功能说明:修改技师信息
     */
    public function coachUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $this->cap_info['id']
        ];

        if(!empty($input['id_card'])){

            $input['id_card'] = implode(',',$input['id_card']);
        }

        if(!empty($input['license'])){

            $input['license'] = implode(',',$input['license']);
        }

        if(!empty($input['self_img'])){

            $input['self_img'] = implode(',',$input['self_img']);
        }

        $res = $this->model->dataUpdate($dis,$input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function index(){

        $data = $this->getUserInfo();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function orderList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.coach_id','=',$this->cap_info['id']];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if($input['pay_type']==5){

            $dis[] = ['a.pay_type','in',[3,4,5]];

        }else{

            $dis[] = ['a.pay_type','=',$input['pay_type']];

        }

        $order_model = new Order();

        $data = $order_model->indexDataList($dis,$where);
        //待接单数量
        $data['agent_order_count'] = $order_model->where(['coach_id'=>$this->cap_info['id'],'pay_type'=>2])->count();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-07 23:11
     * @功能说明:订单详情
     */
    public function orderInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['order_id']
        ];

        $data = $this->order_model->dataInfo($dis);

        return $this->success($data);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-03-24 13:33
     * @功能说明:团长审核提现
     */
    public function applyWallet(){

        $input = $this->_input;

        if(empty($input['apply_price'])||$input['apply_price']<0.01){

            $this->errorMsg('提现费最低一分');
        }
        //服务费
        if($input['apply_price']>$this->cap_info['service_price']&&$input['type']==1){

            $this->errorMsg('余额不足');
        }
        //车费
        if($input['apply_price']>$this->cap_info['car_price']&&$input['type']==2){

            $this->errorMsg('余额不足');
        }

        $coach_level = $this->model->getCoachLevel($this->cap_info['id'],$this->_uniacid);

       // dump($coach_level);exit;
        //车费没有服务费
        $balance = !empty($coach_level)&&$input['type']==1?$coach_level['balance']:100;

        $key = 'cap_wallet'.$this->getUserId();

        $value = getCache($key);

        if(!empty($value)){

            $this->errorMsg('网络错误，请刷新重试');

        }
        //加一个锁防止重复提交
        incCache($key,1,$this->_uniacid);

        Db::startTrans();

        if($input['type']==1){
            //减佣金
            $res = $this->model->dataUpdate(['id'=>$this->cap_info['id']],['service_price'=>$this->cap_info['service_price']-$input['apply_price']]);

        }else{

            $res = $this->model->dataUpdate(['id'=>$this->cap_info['id']],['car_price'=>$this->cap_info['car_price']-$input['apply_price']]);

        }

        if($res!=1){

            Db::rollback();
            //减掉
            delCache($key,$this->_uniacid);

            $this->errorMsg('申请失败');
        }

        $insert = [

            'uniacid'       => $this->_uniacid,

            'user_id'       => $this->getUserId(),

            'coach_id'      => $this->cap_info['id'],

            'total_price'   => $input['apply_price'],

            'balance'       => $balance,

            'apply_price'   => round($input['apply_price']*$balance/100,2),

            'service_price' => round($input['apply_price']-$input['apply_price']*$balance/100,2),

            'code'          => orderCode(),

            'text'          => $input['text'],

            'type'          => $input['type'],

        ];

        $wallet_model = new Wallet();
        //提交审核
        $res = $wallet_model->dataAdd($insert);

        if($res!=1){

            Db::rollback();
            //减掉
            delCache($key,$this->_uniacid);

            $this->errorMsg('申请失败');
        }

        Db::commit();
        //减掉
        delCache($key,$this->_uniacid);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 17:14
     * @功能说明:楼长核销订单
     */
    public function hxOrder(){

        $input = $this->_input;

        $order_model= new Order();

        $order = $order_model->dataInfo(['id'=>$input['id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if($order['pay_type']!=5){

            $this->errorMsg('订单状态错误');
        }

        if($order['coach_id']!=$this->cap_info['id']){

            $this->errorMsg('你不是该订单的楼长');

        }

        $refund_model = new RefundOrder();
        //判断有无申请中的退款订单
        $refund_order = $refund_model->dataInfo(['order_id'=>$order['id'],'status'=>1]);

        if(!empty($refund_order)){

            $this->errorMsg('该订单正在申请退款，请先处理再核销');

        }

        $res = $order_model->hxOrder($order,$this->cap_info['id']);

        return $this->success($res);


    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-30 13:38
     * @功能说明:团长端佣金信息
     */
    public function capCashInfo(){

        $this->order_model->coachBalanceArr($this->_uniacid);

        $key = 'cap_wallet'.$this->getUserId();
        //减掉
        delCache($key,$this->_uniacid);

        $wallet_model = new Wallet();
        //可提现佣金
        $data['cap_cash'] = $this->cap_info['service_price'];
        //累计提现
        $data['extract_total_price'] = $wallet_model->capCash($this->cap_info['id'],2,1);
        //提现中
        $data['extract_ing_price']  = $wallet_model->capCash($this->cap_info['id'],1,1);

        $dis = [

            'pay_type' => 7,

            'coach_id' => $this->cap_info['id'],

            'have_tx'  => 0
        ];
        //未到账
        $data['no_received']  = $this->order_model->where($dis)->sum('service_price');

        $data['coach_level']  = $this->model->getCoachLevel($this->cap_info['id'],$this->_uniacid);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-30 13:38
     * @功能说明:团长端佣金信息
     */
    public function capCashInfoCar(){

        $key = 'cap_wallet'.$this->getUserId();
        //减掉
        delCache($key,$this->_uniacid);

        $wallet_model = new Wallet();
        //可提现佣金
        $data['cap_cash'] = $this->cap_info['car_price'];
        //累计提现
        $data['extract_total_price'] = $wallet_model->capCash($this->cap_info['id'],2,2);
        //提现中
        $data['extract_ing_price']  = $wallet_model->capCash($this->cap_info['id'],1,2);

        $dis = [

            'pay_type' => 7,

            'coach_id' => $this->cap_info['id'],

            'have_tx'  => 0
        ];
        //未到账
        $data['no_received']  = $this->order_model->where($dis)->sum('car_price');

        $data['coach_level']  = $this->model->getCoachLevel($this->cap_info['id'],$this->_uniacid);

        return $this->success($data);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-30 14:39
     * @功能说明:团长提现记录
     */
    public function capCashList(){

        $wallet_model = new Wallet();

        $input = $this->_param;

        $dis = [

            'coach_id' => $this->cap_info['id']
        ];

        if(!empty($input['status'])){

            $dis['status'] = $input['status'];
        }

        $dis['type'] = $input['type'];
        //提现记录
        $data = $wallet_model->dataList($dis,10);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }
        //累计提现
        $data['extract_total_price'] = $wallet_model->capCash($this->cap_info['id'],2,$input['type']);

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-08 17:09
     * @功能说明:报警
     */
    public function police(){

        $insert = [

            'uniacid' => $this->_uniacid,

            'coach_id'=> $this->cap_info['id'],

            'user_id' => $this->cap_info['user_id'],

            'text'    => '正在发出求救信号，请及时查看技师正在服务的订单地址和电话，确认报警信息'
        ];


        $police_model = new Police();

        $res = $police_model->dataAdd($insert);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-11 22:34
     * @功能说明:技师修改订单信息)
     */
    public function updateOrder(){

        $input  = $this->_input;

        $order  = $this->order_model->dataInfo(['id'=>$input['order_id']]);

        $update = $this->order_model->coachOrdertext($input);

        Db::startTrans();
        //核销订单
        if($input['type']==7){

            if($order['pay_type']!=6){

                $this->errorMsg('订单状态错误');
            }

            $refund_model = new RefundOrder();
            //判断有无申请中的退款订单
            $refund_order = $refund_model->dataInfo(['order_id'=>$order['id'],'status'=>1]);

            if(!empty($refund_order)){

                $this->errorMsg('该订单正在申请退款，请先处理再核销');

            }

            $res = $this->order_model->hxOrder($order,$this->cap_info['id']);

            $res = $this->order_model->dataUpdate(['id'=>$input['order_id']],$update);

        }else{

//            dump($update);exit;

            $res = $this->order_model->dataUpdate(['id'=>$input['order_id']],$update);
            //拒绝接单
            if($input['type']==-1){

                if($order['pay_type']!=2){

                    Db::rollback();

                    $this->errorMsg('已接单');

                }

                if($order['pay_price']>0){

                    $refund_model = new RefundOrder();

                    $res = $refund_model->refundCash($this->payConfig(),$order,$order['pay_price']);

                    if(!empty($res['code'])){

                        Db::rollback();

                        $this->errorMsg($res['msg']);

                    }

                    if($res!=true){

                        Db::rollback();

                        $this->errorMsg('退款失败，请重试2');

                    }
                }


            }

        }

        Db::commit();

        return $this->success($res);



    }









}
